package com.xiaobingby.common.utils;

import com.xiaobingby.common.entity.TreeNode;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 李磊
 * @date 2019/5/8
 */
public class TreeUtil {
    public static <T> List<TreeNode> getTrees(List<T> list,boolean setUrl,boolean setChecked){
        Map<Long,TreeNode> treeMap = new HashMap<Long,TreeNode>();
        for (T t : list) {
            TreeNode tree = new TreeNode();
            toTreeNode(t,tree,setUrl,setChecked);
            treeMap.put(tree.getId(), tree);
        }
        List<TreeNode> retList = new ArrayList<TreeNode>();
        for(Map.Entry<Long, TreeNode> entry:treeMap.entrySet()){
            Long pid = entry.getValue().getPid();
            TreeNode pTreeNode = treeMap.get(pid);
            if(pTreeNode != null){
                entry.getValue().setParentNode(pTreeNode);
                pTreeNode.addChild(entry.getValue());
            }else{
                retList.add(entry.getValue());
            }
        }
        //将parentNode置null，否则gson无法转换，fastjson可以
        setParentNodeNull(retList);
        return retList;
    }

    private static void setParentNodeNull(List<TreeNode> list){
        for (TreeNode treeNode : list) {
            treeNode.setParentNode(null);
            setParentNodeNull(treeNode.getChildren());
        }
    }

    private static <T> void toTreeNode(T t, TreeNode tree,boolean setUrl,boolean setChecked){
        try {
            Field id = t.getClass().getDeclaredField("id");
            id.setAccessible(true);
            Field pid = t.getClass().getDeclaredField("pid");
            pid.setAccessible(true);
            Field name = t.getClass().getDeclaredField("name");
            name.setAccessible(true);

            tree.setId((Long) id.get(t));
            tree.setPid((Long) pid.get(t));
            tree.setIconCls("");
            tree.setText((String) name.get(t));


            if(setUrl){
                Field url = t.getClass().getDeclaredField("url");
                url.setAccessible(true);
                Map<String, String> attributeMap = new HashMap<String, String>();
                attributeMap.put("url", (String) url.get(t));
                tree.setAttributes(attributeMap);
            }
            if(setChecked){
                Field checked = t.getClass().getDeclaredField("checked");
                checked.setAccessible(true);
                tree.setChecked((Boolean) checked.get(t));
            }

            tree.setState("open");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
